#!/bin/bash - 
#===============================================================================
#
#          FILE: reviewManager.sh
# 
#         USAGE: ./reviewManager.sh 
# 
#   DESCRIPTION: the manager of review knowledge, the rule of review
#                2^n (n<=6)
# 
#       OPTIONS: ---
#  REQUIREMENTS: ---
#          BUGS: ---
#         NOTES: ---
#        AUTHOR: YOUR NAME (), 
#  ORGANIZATION: 
#       CREATED: 02/01/2021 18:45
#      REVISION:  ---
#===============================================================================

set -o nounset                              # Treat unset variables as an error

#---  FUNCTION  ----------------------------------------------------------------#          NAME:  getWorkDir
#   DESCRIPTION:  get the directory where current shell program locates
#    PARAMETERS:
#       RETURNS:
#-------------------------------------------------------------------------------
getWorkDir()
{
    baseDir=$(dirname $0)
    if [ ${baseDir} = '.' ]; then
        echo "$(pwd)"
    elif [ ${baseDir:0:1} = '/' ]; then
        echo "${baseDir}"
    else
        echo "$(pwd)/${baseDir}"
    fi
}

generateIncId()
{
    if [ ! -e $CONFIG_FILE ]  ; then
        currentId=1
        echo 'current_id=1' > "$CONFIG_FILE"
        echo $currentId
        return 0
    fi

    currentId=$(grep 'current_id' "$CONFIG_FILE"|sed 's/current_id=\(.*\)$/\1/')
    let currentId++

    # update to config file
    sed -i "s/current_id=.*\$/current_id=$currentId/" "$CONFIG_FILE"

    echo $currentId
}

#---  FUNCTION  ----------------------------------------------------------------
#          NAME:  addReviewTask
#   DESCRIPTION:  add Task to File 
#    PARAMETERS:  
#       RETURNS:  
#-------------------------------------------------------------------------------
addReviewTask()
{
    #     checkScheduleExecuting || return 1

    # read params
    read -p "What's your task? (character[/,$] not support) " taskName

    # validate params 
    if [ -z "$taskName" ]  ; then
        echo -e "\e[1;31mTask name shouldn't be empty\e[0m";
        return 1;
    fi


    beginTime=$(date '+%s')
    resetTime=$(date --date "$(date '+%Y-%m-%d')" '+%s')

    taskId=$(generateIncId)

    #TODO: bug
    finalTaskName=$(echo $taskName | tr -s ' '|tr -d '\t')

    echo -e "$taskId\t$finalTaskName\t$beginTime\t0\t$resetTime" >> $STORE_FILE
    echo -e "\e[1;32mAdd Success!!!\e[0m"
}

#---  FUNCTION  ----------------------------------------------------------------
#          NAME:  showReviewTask
#   DESCRIPTION:  show all the task 
#    PARAMETERS:  
#       RETURNS:  
#-------------------------------------------------------------------------------
showReviewTask()
{
    printf "\n\e[1;33m%-5s\t%-60s\t%-16s\t%-16s\t%-16s\e[0m\n" "ID"  "Task" "Add Time" "Next Review Time" "Last Reset Time"
    [ -e $STORE_FILE ] || return 0;
    lineNo=$(cat "$STORE_FILE" | wc -l)
    [ $lineNo -eq 0 ] && return 0;
    cat "$STORE_FILE" | sort -t$'\t' -k3g |  awk  -F '\t' '{
    printf "%-5s\t",$1
    printf "%-60s\t",$2
    time=strftime("%Y-%m-%d %H:%M",$3);printf "%-16s\t",time
    if($4=="-"){
        printf "\033[1;32m%-16s\033[0m\t","End"
    }else{
        nextreview=2 ^ $4 * 3600 * 24 + $5
        nexttime=strftime("%Y-%m-%d",nextreview);
        todaytime=strftime("%Y-%m-%d", systime());
        if(todaytime == nexttime){
            printf "\033[1;31m%-16s\033[0m\t",nexttime
        }else{
            printf "%-16s\t",nexttime
        }
    }
    resettime=strftime("%Y-%m-%d",$5);printf "%-16s\n",resettime
}';    
}

#---  FUNCTION  ----------------------------------------------------------------
#          NAME:  findTaskById
#   DESCRIPTION:   
#    PARAMETERS:  id, ifGetLineNo=[0: yes, 1:no]
#       RETURNS:  [lineno]:[content]
#-------------------------------------------------------------------------------
findTaskById()
{

    if [ ! $# -eq 2 ] ; then
        exit 1;  
    fi
    ID=$1
    ifGetLineNo=$2

    [ ! $ifGetLineNo -eq 0 ] &&  [ ! $ifGetLineNo -eq 1 ] && exit 1;

    taskContent=$(cat "$STORE_FILE")

    #validate the id
    tab=$'\t'
    if [ $ifGetLineNo -eq 0 ] ; then
        record=$(echo "$taskContent" | grep -En  "^$ID$tab")
    else
        record=$(echo "$taskContent" | grep -E  "^$ID$tab")
    fi

    if [ -z "$record" ]   ; then
        return 1;
    else
        echo "$record"
    fi
}

#---  FUNCTION  ----------------------------------------------------------------
#          NAME:  resetReviewTask
#   DESCRIPTION: Task 
#    PARAMETERS:  
#       RETURNS:  
#-------------------------------------------------------------------------------
resetReviewTask()
{
    #     checkScheduleExecuting || return 1
    while : ; do
        echo -en "\e[1;36mReset the task, enter the 'ID' or 'q'(quit): \e[0m" 
        read ID
        [[ $ID == 'q' ]] && return 0;

        record=$(findTaskById $ID 1)

        if [ $? -eq 1 ] ; then
            echo -e "\e[1;31m Invalid Id \e[0m"
        else
            todayTime=$(date --date "$(date '+%Y-%m-%d')" '+%s')
            replaceStr=$(echo "$record"|awk -F$'\t' '{
            print $1 "\t" $2 "\t" $3 "\t" 0 "\t" resetTime;
            }' resetTime=$todayTime) 
            sed -i "s/^$ID.\+\$/$replaceStr/" "$STORE_FILE"
            echo -e "$ID\t$(date '+%s')\treset" >> "$LOG_FILE"
            echo -e "\e[1;32mReset success!\e[0m";
        fi
        showReviewTask;
    done
}

confirmReviewTask()
{
    while : ; do
        echo -en "\e[1;36mConfirm the task is reviewed, enter the 'ID' or 'q'(quit): \e[0m" 
        read ID
        [[ $ID == 'q' ]] && return 0;

        record=$(findTaskById $ID 1)

        if [ $? -eq 1 ] ; then
            echo -e "\e[1;31m Invalid Id \e[0m"
        else
            set -x
            todayTime=$(date --date "$(date '+%Y-%m-%d')" '+%s')
            replaceStr=$(echo "$record"|awk -F$'\t' '{
            if($4=="-"){
                print "end"
            }else{
                nextreview=2 ^ $4 * 3600 * 24 + $5
                if(nextreview==resetTime){
                    if($4 + 1 > 5){
                        print $1 "\t" $2 "\t" $3 "\t" - "\t" $5;
                    }else{
                        print $1 "\t" $2 "\t" $3 "\t" $4+1 "\t" $5;
                    }   
                }else{
                    print "" 
                }
            }
            }' resetTime=$todayTime) 
            
           
            if [ -n "$replaceStr" ] ; then
                if [[ "$replaceStr" == "end" ]] ; then
                    echo -e "\e[1;31m This task is end \e[0m"
                    continue
                fi
                sed -i "s/^$ID.\+\$/$replaceStr/" "$STORE_FILE"
                echo -e "$ID\t$(date '+%s')\treviewed" >> "$LOG_FILE"
                echo -e "\e[1;32mConfirm success!\e[0m";
            else
                echo -e "\e[1;31m This task can't confirm today \e[0m"
            fi
            set +x
        fi
        showReviewTask;
    done

}

export WORKDIR=$(getWorkDir)
. "$WORKDIR"/common.sh

showReviewTask;

while : ; do
    echo 
    echo -en "\e[1;36mAdd[a] Reset[r] Confirm[c] Quit[q]: \e[0m";
    read option
    if [[ "$option" == 'a'  ]]  ; then 
        addReviewTask; 
    elif [[ "$option" == 'r'  ]] ; then
        resetReviewTask;
    elif [[ "$option" == 'c'  ]] ; then
        confirmReviewTask;
    elif [[ "$option" == 'q'  ]] ; then
        echo -e "\e[1;36mGoodbye!"
        exit;
    fi
    showReviewTask;
done
